package cn.com.libertymutual.sp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import cn.com.libertymutual.core.base.dto.AgreementCodeRequestDto;
import cn.com.libertymutual.core.base.dto.TQueryLmAgentResponseDto;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.BeanUtilExt;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.util.enums.CoreServiceEnum;
import cn.com.libertymutual.core.util.uuid.UUID;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.sp.bean.SysOperationLog;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.dao.OperationLogDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.TQuerySalesRequestDto;
import cn.com.libertymutual.sp.dto.TQuerySalesResponseDto;
import cn.com.libertymutual.sp.service.api.BranchSetService;
import cn.com.libertymutual.sp.service.api.InitService;
import cn.com.libertymutual.sys.bean.SysCodeNode;
import cn.com.libertymutual.sys.bean.SysServiceInfo;
import cn.com.libertymutual.sys.dao.ISysCodeNodeDao;
import cn.com.libertymutual.sys.service.api.IInitSharedMemory;

@Service("branchSetService")
public class BranchSetServiceImpl implements BranchSetService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private TbSysHotareaDao tbSysHotareaDao;
	@Resource
	private RestTemplate restTemplate;
	@Resource
	private InitService initService;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private OperationLogDao operationLogDao;
	@Autowired
	private ISysCodeNodeDao codeNodeDao;
	@Autowired
	private IInitSharedMemory initSharedMemory;
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private TbSysHotareaDao hotareaDao;
	
	
	@Override
	public String getUserCodeBranchCode(String userCode) {
		if(StringUtils.isNotBlank(userCode)) {
			TbSpUser user =  userDao.findByUserCode(userCode);
			if( user == null ) {
				log.info("userCode={}", userCode);
				return "";
			}
			
			if(StringUtils.isNotBlank(user.getBranchCode())) {
				return user.getBranchCode();
			}else if(user!=null&&StringUtils.isNotBlank(user.getAreaCode())) {
				TbSysHotarea hotArea = hotareaDao.findByAreaCode(user.getAreaCode());
				if(hotArea==null) {
					return "";
				}else {
					return hotArea.getBranchCode();
				}
			}	
		}
		return "";
		
	}
	
	@Override
	public ServiceResult areaList(String branchCode, int pageNumber, int pageSize) {

		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
		if (StringUtils.isEmpty(branchCode) || "-1".equals(branchCode)) {
			sr.setResult(tbSysHotareaDao.findAllArea(pageable));
		} else {
			sr.setResult(tbSysHotareaDao.findByBranchCode(branchCode, pageable));
		}
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult addArea(String agreementNo, String saleCode, String saleName, String branchCode, String branchName, String[] list,
			String invoiceStatus, String insurancePolicyStatus, String contactMobile, String contactEmail) {
		ServiceResult sr = new ServiceResult();

		if (StringUtils.isBlank(agreementNo)) {
			sr.setFail();
			sr.setResult("业务关系代码为空!");
			return sr;
		}
		// 获取业务关系代码查询基本信息
		@SuppressWarnings("rawtypes")
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.FindAgentInfoByAgreementCode_URL.getUrlKey());

		HttpHeaders headers = RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword(),
				MediaType.APPLICATION_JSON);

		// 请求参数对象
		AgreementCodeRequestDto agreementCodeRequestDto = new AgreementCodeRequestDto();
		agreementCodeRequestDto.setAgreementCode(agreementNo);
		agreementCodeRequestDto.setFlowId(sysServiceInfo.getUserName() + UUID.getUUIDString());
		agreementCodeRequestDto.setOperatorDate(String.valueOf(new Date().getTime()));
		agreementCodeRequestDto.setPartnerAccountCode(sysServiceInfo.getUserName());
		// 请求体
		HttpEntity<AgreementCodeRequestDto> requestEntity = new HttpEntity<AgreementCodeRequestDto>(agreementCodeRequestDto, headers);
		// 请求接口
		ResponseEntity<TQueryLmAgentResponseDto> responseEntity = restTemplate.exchange(sysServiceInfo.getUrl(), HttpMethod.POST, requestEntity,
				TQueryLmAgentResponseDto.class);
		// 返回实体
		TQueryLmAgentResponseDto responseDto = responseEntity.getBody();
		if (CollectionUtils.isEmpty(responseDto.getPrpLmAgentList())) {
			sr.setFail();
			sr.setResult("未配置的业务关系代码！");
			return sr;
		}
		tbSysHotareaDao.updateAgreementNo(agreementNo, saleCode, saleName, invoiceStatus, insurancePolicyStatus, contactMobile, contactEmail,
				branchCode);

		for (int i = 0; i < list.length; i++) {
			TbSysHotarea dbarea = tbSysHotareaDao.findByBranchCodeAndAreaCode(branchCode, list[i]);
			if (null != dbarea) {
				dbarea.setStatus("1");
				tbSysHotareaDao.save(dbarea);
				SysOperationLog operLog = new SysOperationLog();
				operLog.setIP(Current.IP.get());
				operLog.setLevel("1");
				operLog.setModule("机构配置");
				operLog.setOperationTime(new Date());
				operLog.setUserId(Current.userInfo.get().getUserId());
				operLog.setContent("给" + dbarea.getBranchName() + "添加地区" + ",地区名:" + dbarea.getAreaName());
				operationLogDao.save(operLog);
				sr.setSuccess();
			} else {
				try {
					HashMap<String, Map<String, SysCodeNode>> codeMap = (HashMap<String, Map<String, SysCodeNode>>) redisUtils
							.get(Constants.MAP_CODE);
					SysCodeNode branch = codeMap.get("BranchCode").get(branchCode);
					SysCodeNode area = codeMap.get("AREACODE").get(list[i]);
					TbSysHotarea tbSysHotarea = new TbSysHotarea();
					tbSysHotarea.setBranchCode(branchCode);
					tbSysHotarea.setBranchName(branch.getCodeCname());
					tbSysHotarea.setBranchEname(branch.getCodeEname());
					tbSysHotarea.setAreaCode(list[i]);
					tbSysHotarea.setAreaName(area.getCodeCname());
					tbSysHotarea.setAgreementNo(agreementNo);
					tbSysHotarea.setSaleCode(saleCode);
					tbSysHotarea.setSaleName(saleName);
					tbSysHotarea.setStatus("1");
					tbSysHotarea.setInsurancePolicyStatus(insurancePolicyStatus);
					tbSysHotarea.setInvoiceStatus(invoiceStatus);
					TbSysHotarea newarea = tbSysHotareaDao.save(tbSysHotarea);
					sr.setResult(newarea);

					SysOperationLog operLog = new SysOperationLog();
					operLog.setIP(Current.IP.get());
					operLog.setLevel("1");
					operLog.setModule("机构配置");
					operLog.setOperationTime(new Date());
					operLog.setUserId(Current.userInfo.get().getUserId());
					operLog.setContent("给" + branch.getCodeCname() + "添加地区" + ",地区名:" + area.getCodeCname());
					operationLogDao.save(operLog);
				} catch (Exception e) {
					sr.setResult("数据异常！");
				}

			}
		}
		// 更新redis缓存
		Map<String, List<TbSysHotarea>> branchMap = (Map<String, List<TbSysHotarea>>) redisUtils.get(Constants.BRANCH_AREA_INFO);
		List<TbSysHotarea> branchAreaList = tbSysHotareaDao.findByBranchCode(branchCode);
		branchMap.put(branchCode, branchAreaList);
		// List<TbSysHotarea> numList = tbSysHotareaDao.findAllArea();
		// redisUtils.set(Constants.ALL_AREA_INFO, numList);
		redisUtils.set(Constants.BRANCH_AREA_INFO, branchMap);
		log.info("----------add缓存更新成功！--------------");
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult removeArea(String agreementNo, String saleCode, String saleName, String branchCode, String[] list, String invoiceStatus,
			String insurancePolicyStatus, String contactMobile, String contactEmail) {
		ServiceResult sr = new ServiceResult();
		if (StringUtils.isBlank(agreementNo)) {
			sr.setFail();
			sr.setResult("业务关系代码为空!");
			return sr;
		}
		// 获取业务关系代码查询基本信息
		@SuppressWarnings("rawtypes")
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.FindAgentInfoByAgreementCode_URL.getUrlKey());

		HttpHeaders headers = RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword(),
				MediaType.APPLICATION_JSON);

		// 请求参数对象
		AgreementCodeRequestDto agreementCodeRequestDto = new AgreementCodeRequestDto();
		agreementCodeRequestDto.setAgreementCode(agreementNo);
		agreementCodeRequestDto.setFlowId(sysServiceInfo.getUserName() + UUID.getUUIDString());
		agreementCodeRequestDto.setOperatorDate(String.valueOf(new Date().getTime()));
		agreementCodeRequestDto.setPartnerAccountCode(sysServiceInfo.getUserName());
		// 请求体
		HttpEntity<AgreementCodeRequestDto> requestEntity = new HttpEntity<AgreementCodeRequestDto>(agreementCodeRequestDto, headers);
		// 请求接口
		ResponseEntity<TQueryLmAgentResponseDto> responseEntity = restTemplate.exchange(sysServiceInfo.getUrl(), HttpMethod.POST, requestEntity,
				TQueryLmAgentResponseDto.class);
		// 返回实体
		TQueryLmAgentResponseDto responseDto = responseEntity.getBody();
		if (CollectionUtils.isEmpty(responseDto.getPrpLmAgentList())) {
			sr.setFail();
			sr.setResult("未配置的业务关系代码！");
			return sr;
		}

		for (int i = 0; i < list.length; i++) {
			TbSysHotarea dbarea = tbSysHotareaDao.findByBranchCodeAndAreaCode(branchCode, list[i]);
			if (null != dbarea) {
				if ("1".equals(dbarea.getStatus())) {
					dbarea.setStatus("0");
					tbSysHotareaDao.save(dbarea);
					SysOperationLog operLog = new SysOperationLog();
					operLog.setIP(Current.IP.get());
					operLog.setLevel("3");
					operLog.setModule("机构配置");
					operLog.setOperationTime(new Date());
					operLog.setUserId(Current.userInfo.get().getUserId());
					operLog.setContent("删除了" + dbarea.getBranchName() + "下的地区:" + dbarea.getAreaName());
					operationLogDao.save(operLog);

					sr.setSuccess();
				}
			} else {
				log.info("未添加过的areaCode:" + list[i]);
			}
		}
		// 修改业务关系代码
		tbSysHotareaDao.updateAgreementNo(agreementNo, saleCode, saleName, invoiceStatus, insurancePolicyStatus, contactMobile, contactEmail,
				branchCode);
		// 更新redis缓存
		Map<String, List<TbSysHotarea>> branchMap = (Map<String, List<TbSysHotarea>>) redisUtils.get(Constants.BRANCH_AREA_INFO);
		List<TbSysHotarea> branchAreaList = tbSysHotareaDao.findByBranchCode(branchCode);
		branchMap.put(branchCode, branchAreaList);
		// List<TbSysHotarea> numList = tbSysHotareaDao.findAllArea();
		// redisUtils.set(Constants.ALL_AREA_INFO, numList);
		redisUtils.set(Constants.BRANCH_AREA_INFO, branchMap);
		log.info("----------remove缓存更新成功！--------------");
		return sr;
	}

	@Override
	public ServiceResult getAgreementNo(String branchCode) {

		ServiceResult sr = new ServiceResult();
		try {
			// Map<String, List<TbSysHotarea>> map = (Map<String, List<TbSysHotarea>>)
			// redisUtils
			// .get(Constants.BRANCH_AREA_INFO);
			// log.info("================map=================" + map);
			if (StringUtils.isNotEmpty(branchCode)) {
				// List<TbSysHotarea> tbSysHotarea = map.get(branchCode);
				List<TbSysHotarea> tbSysHotarea = tbSysHotareaDao.findByBranchCode(branchCode);
				sr.setResult(tbSysHotarea.get(0));
				sr.setSuccess();
			} else {
				sr.setFail();
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			sr.setFail();
		}
		return sr;
	}

	@Override
	public ServiceResult notConfiguredArea(String branchCode) {
		ServiceResult sr = new ServiceResult();
		try {
			Map<String, List<SysCodeNode>> map3 = (HashMap<String, List<SysCodeNode>>) redisUtils.get(Constants.lIMIT_LIST_CODE);
			List<SysCodeNode> codeList = map3.get("AREACODE");
			// Map<String, List<TbSysHotarea>> branchMap = (Map<String, List<TbSysHotarea>>)
			// redisUtils
			// .get(Constants.BRANCH_AREA_INFO);
			List<SysCodeNode> notArea = new ArrayList<SysCodeNode>();
			List<String> dbAllArea = tbSysHotareaDao.findAllAreaCode();
			// List<TbSysHotarea> dbArea = branchMap.get(branchCode);
			List<TbSysHotarea> dbArea = tbSysHotareaDao.findByBranchCode(branchCode);
			for (int i = 0; i < codeList.size(); i++) {
				if (!dbAllArea.contains(codeList.get(i).getCode())) {
					notArea.add(codeList.get(i));
				}
				if (null != dbArea && dbArea.size() != 0) {
					for (int j = 0; j < dbArea.size(); j++) {
						if (codeList.get(i).getCode().equals(dbArea.get(j).getAreaCode())) {
							notArea.add(codeList.get(i));
							break;
						}
					}
				}
			}
			sr.setResult(notArea);
		} catch (Exception e) {
			log.info(e.getMessage());
			sr.setFail();
		}

		return sr;
	}

	@Override
	public ServiceResult getSaleName(String agreementCode) {
		ServiceResult sr = new ServiceResult();
		log.info("agreementCode--->:{}", agreementCode);
		TQuerySalesRequestDto request = new TQuerySalesRequestDto(agreementCode, "");
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.QUERY_SALE_NAME.getUrlKey());
		log.info("sysServiceInfo------------>:{}", sysServiceInfo);
		request.setPartnerAccountCode(sysServiceInfo.getUserName());
		request.setFlowId(request.getPartnerAccountCode() + new Date().getTime());
		log.info(BeanUtilExt.toJsonString(request));
		/*
		 * HttpHeaders headers = new HttpHeaders(); headers.add("account-code",
		 * sysServiceInfo.getUserName()); headers.add("request-time", String.valueOf(new
		 * Date().getTime())); headers.add("soa-token",
		 * pwdEncoder.encodePassword(sysServiceInfo.getPassword(), String.valueOf(new
		 * Date().getTime())));
		 */
		HttpEntity<TQuerySalesRequestDto> requestEntity = new HttpEntity<TQuerySalesRequestDto>(request,
				RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword()));

		TQuerySalesResponseDto response = restTemplate.postForObject(sysServiceInfo.getUrl(), requestEntity, TQuerySalesResponseDto.class);
		log.info("getSaleName response--->:{}", response);
		sr.setResult(response);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult addNewArea(String branchCode, String branchName, String areaCode, String areaName, String areaEname) {
		ServiceResult sr = new ServiceResult();
		// 校验地区编码是否存在
		HashMap<String, Map<String, SysCodeNode>> codeMap = (HashMap<String, Map<String, SysCodeNode>>) redisUtils.get(Constants.MAP_CODE);
		SysCodeNode branch = codeMap.get("AREACODE").get(areaCode);
		if (null != branch) {
			sr.setFail();
			sr.setResult("地区编码已经存在！请确认。");
			return sr;
		}
		SysCodeNode sysCoden = new SysCodeNode();
		sysCoden.setCodeType("AREACODE");
		sysCoden.setCode(areaCode);
		sysCoden.setCodeCname(areaName);
		sysCoden.setCodeEname(areaEname);
		sysCoden.setValidStatus(Constants.TRUE);
		sysCoden.setSerialNo(1);
		codeNodeDao.save(sysCoden);
		if (StringUtils.isNotEmpty(branchCode) && StringUtils.isNotEmpty(branchName)) {// 需要配置hotarea表
			List<TbSysHotarea> dbhotArea = tbSysHotareaDao.findByBranchCode(branchCode);
			TbSysHotarea hotArea = new TbSysHotarea();
			if (null != dbhotArea && dbhotArea.size() != 0) {
				hotArea.setAgreementNo(dbhotArea.get(0).getAgreementNo());
				hotArea.setSaleCode(dbhotArea.get(0).getSaleCode());
				hotArea.setSaleName(dbhotArea.get(0).getSaleName());
				hotArea.setBranchEname(dbhotArea.get(0).getBranchEname());
				hotArea.setContactEmail(dbhotArea.get(0).getContactEmail());
				hotArea.setContactMobile(dbhotArea.get(0).getContactMobile());
				hotArea.setInsurancePolicyStatus(dbhotArea.get(0).getInsurancePolicyStatus());
				hotArea.setInvoiceStatus(dbhotArea.get(0).getInvoiceStatus());
			}
			hotArea.setAreaCode(areaCode);
			hotArea.setStatus(Constants.TRUE);
			hotArea.setAreaName(areaName);
			hotArea.setBranchCode(branchCode);
			hotArea.setBranchName(branchName);
			tbSysHotareaDao.save(hotArea);
		}

		// 刷新缓存
		initService.initData();
		initSharedMemory.initCodeInto();
		return sr;
	}

	@Override
	public String cutBranchCode(String branchCode) {
		//if (branchCode.indexOf("3399") < 0 &&branchCode.indexOf("1301") < 0) {这个方法不严谨
		if ( !branchCode.startsWith("3399") && !branchCode.startsWith("1301") ) {
			return branchCode.substring(0, 2) + "00";
		} else {
			// 浙江、宁波
			return branchCode.substring(0, 4);
		}
	}

}
